﻿namespace SalaryTool.Service.Controllers
{
    using System.Collections.Generic;
    using System.Configuration;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Web;
    using System.Web.Http;
    using SalaryTool.Service.Models;

    public class EmployeeController : ApiController
    {
        private readonly IEmployeeDataSource employeeDataSource;

        public EmployeeController()
        {
            string employeeDataFilePath = ConfigurationManager.AppSettings["employeeDataFile"];

            try
            {
                employeeDataFilePath = HttpContext.Current.Server.MapPath(employeeDataFilePath);
            }
            catch (HttpException)
            {
            }

            this.employeeDataSource = new EmployeeFileDataSource(employeeDataFilePath);
        }

        public IEnumerable<Employee> Get()
        {
            IList<Employee> employees = this.employeeDataSource.GetEmployees();

            if (employees == null || employees.Count == 0)
            {
                var responseMessage = new HttpResponseMessage(HttpStatusCode.NotFound)
                {
                    Content = new StringContent("The company has no employees."),
                    ReasonPhrase = "No Employees"
                };

                throw new HttpResponseException(responseMessage);
            }

            return employees;
        }

        public Employee PostMarketMultiplier(Employee employee)
        {
            this.employeeDataSource.UpdateMarketMultiplier(employee.Id, employee.MarketPercentageMultiplier);

            return this.employeeDataSource.GetEmployees().SingleOrDefault<Employee>(e => e.Id == employee.Id);
        }
    }
}
